﻿namespace PageTypeBuilderUI
{
    using EPiServer.Core;
    using System.IO;
    using System.Reflection;
    using System.Xml;

    public static class LanguageHelper
    {
        private static XmlDocument _document;

        public static string Translate(string xpath)
        {
            return LanguageManager.Instance.TranslateFallback(xpath, LanguageHelper.GetFallbackText(xpath));
        }

        private static string GetFallbackText(string xpath)
        {
            if (_document == null)
            {
                string xml = string.Empty;

                using (Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PageTypeBuilderUI.lang.lang_EN.xml"))
                {
                    using (StreamReader streamReader = new StreamReader(manifestResourceStream))
                    {
                        xml = streamReader.ReadToEnd();
                    }
                }
                _document = new XmlDocument();
                _document.LoadXml(xml);
            }

            if (!xpath.StartsWith("/"))
                xpath = "/" + xpath;
            
            return _document.SelectSingleNode("/languages/language" + xpath).InnerText.Trim();
        }
    }
}